<?php

declare(strict_types=1);

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerInvite;
use app\common\customer\validate\CustomerInviteValidate;
use util\Format;

class Invite extends Api
{
    /**
     * 分页获取用户的进店数据
     * @return void
     */
    public function getList()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $where = [];
        $where[] = ['create_id', '=', $user['id']];

        list($cfg) = Format::pagination($post);
        $model = new CustomerInvite();
        $pg = $model->where($where)->paginate($cfg);
        $rows = $pg->getCollection();

        foreach ($rows as $row) {
            $row->append(['store', 'creator', 'member', 'status_text']);
        }

        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);
        return success($result, '获取数据成功');
    }

    // 到店列表
    public function index()
    {
        $post = $this->request->post();
        if (empty($post['member_id'])) return error([], "member_id不能为空");
        if (empty($post['allocate_id'])) return error([], "allocate_id不能为空");

        // 校验跟进和member_id的关系
        $allocateModel = new CustomerAllocate();
        $followUp = $allocateModel::withTrashed()->where('id', $post['allocate_id'])->field('id,member_id')->find();
        if (empty($followUp)) return error([], "跟进已不存在或合并");
        if ($followUp['member_id'] != $post['member_id']) return error([], "参数异常");

        $model = new CustomerInvite();
        $list = $model->where('member_id', $post['member_id'])->visible(['id', 'store_id', 'invite_time', 'visit_time', 'remark', 'create_time'])->select();

        foreach ($list as $row) {
            $row->append(['creator', 'store', 'status_text']);
        }

        return success($list);
    }

    // 创建到店
    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        $validate = new CustomerInviteValidate();

        // 验证数据
        if (!$validate->scene('create')->check($post)) return error([], $validate->getError());

        // 写入到店数据
        try {
            $post['status'] = 0;
            $post['create_id'] = $user['id'];
            $model = new CustomerInvite();
            $model->save($post);
        } catch (\Exception $e) {
            return error([], $e->getMessage());
        }

        return success([], "创建到店成功");
    }

    // 更新到店信息
    public function save()
    {
        $post = $this->request->post();
        $validate = new CustomerInviteValidate();

        // 获取到店id
        if (empty($post['id'])) return error([], "id不能为空");
        $id = $post['id'];

        // 验证数据
        if (!$validate->scene('edit')->check($post)) return error([], $validate->getError());

        // 更新到店数据
        try {
            $model = new CustomerInvite();
            $invite = $model->find($id);
            if (empty($invite)) return error([], "到店信息不存在");
            $invite->save($post);
        } catch (\Exception $e) {
            return error([], $e->getMessage());
        }

        return success([], "更新到店成功");
    }

    // 删除到店信息
    public function delete()
    {
        $post = $this->request->post();

        // 获取到店id
        if (empty($post['id'])) return error([], "id不能为空");
        $id = $post['id'];

        // 删除到店数据
        try {
            $model = new CustomerInvite();
            $invite = $model->find($id);
            if (empty($invite)) return error([], "到店信息不存在");
            $invite->delete();
        } catch (\Exception $e) {
            return error([], $e->getMessage());
        }

        return success([], "删除到店成功");
    }


    /**
     * 获取每月的到店数量
     * @return \think\response\Json
     */
    public function grouping(): \think\response\Json
    {
        $post = $this->request->post();
        if (empty($post['month'])) {
            // 获取当前月份的第一天的时间戳
            $firstDay = date('Y-m-01', time());
            $firstDayStamp = strtotime($firstDay);
        } else {
            $month = $post['month'];
            $firstDay = date('Y-m-01', strtotime($month));
            $firstDayStamp = strtotime($firstDay);
        }
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));
        $lastDayStamp = strtotime($lastDay);

        $user = $this->request->user;
        $where = [];
        $where[] = ['create_id', '=', $user['id']];
        $where[] = ['invite_time', 'between', [$firstDayStamp, $lastDayStamp]];

        // 获取每天的到店数量,index为时间
        $model = new CustomerInvite();
        $list = $model->where($where)->field('FROM_UNIXTIME(invite_time, "%Y-%m-%d") as date, count(id) as count')->group('date')->select();

        return success($list);
    }
}
